import { gsap } from 'gsap'
import * as THREE from 'three'
export default class AnimationsModule {
    constructor({ tweenGroup, Tween, Easing }) {
        this.animationsObject = {};
        this.resources = [];
        this.key = '';
        this.clock = new THREE.Clock();
        this.tweenGroup = tweenGroup;
        this.Tween = Tween;
        this.Easing = Easing;
        this.animateId = null;
        this.out = false;
    }
    add(key, value) {
        this.animationsObject[key] = value;
    }
    play(key, duration) {
        cancelAnimationFrame(this.animateId);
        this.key = key;
        this.animationsObject[key]._actions.forEach(action => {
            action.setLoop(THREE.LoopOnce); // 关键：设置为播放一次
            action.clampWhenFinished = true; // 关键：播放完后固定在最后一帧
            action.play();
        })
        this.animationsObject[key].addEventListener('finished', () => {
            this.out = true;
        });
        this.animate();
    }

    animate() {
        if (this.out) {
            cancelAnimationFrame(this.animateId);
        }
        this.animationsObject[this.key]?.update(this.clock.getDelta());
        this.animateId = requestAnimationFrame(() => this.animate());
    }
    reset(key) {
        if (!key || !this.animationsObject[key]) return;
        const mixer = this.animationsObject[key];
        // 1. 停止所有动作
        mixer.stopAllAction();
        // 2. 重置每个动作
        mixer._actions.forEach(action => {
            // 分步操作（不能链式调用）
            action.reset();
            action.setLoop(THREE.LoopRepeat);
            action.clampWhenFinished = false;
            action.time = 0;
        });
        // 3. 强制更新状态
        mixer.update(0);
        this.out = false;
        const router = new this.Tween({},
            this.tweenGroup // 关键：传入组实例
        ).to({}, 1250)
            .easing(this.Easing.Quartic.Out)
            .onUpdate((obj) => {
                this.animationsObject[this.key]?.update(this.clock.getDelta());
            })
            .start().onComplete(() => {
                this.tweenGroup.remove(router);
            })
    }
} 